package com.mazaiting.redeye.module.msg

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.event.MessageEvent
import cn.jpush.im.android.api.model.Conversation
import cn.jpush.im.android.api.model.UserInfo
import com.chad.library.adapter.base.BaseQuickAdapter
import com.mazaiting.easy.app.IApplicationComponent
import com.mazaiting.easy.base.fragment.BaseRefreshFragment
import com.mazaiting.log.L
import com.mazaiting.redeye.R
import com.mazaiting.redeye.base.ApplicationComponentImpl
import com.mazaiting.redeye.event.UpdateEvent
import com.mazaiting.redeye.module.msg.single.SingleActivity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 消息碎片
 */
class MsgFragment : BaseRefreshFragment<MsgPresenter>(), MsgContract.View {

    companion object {
        /**
         * 实例化
         */
        fun newInstance() = MsgFragment()
    }


    override fun lazyFetchData() {
        // 获取消息列表
        val conversationList: List<Conversation> = JMessageClient.getConversationList()
        adapter.setNewData(conversationList)
        L.d("conversationList: $conversationList")
    }

    override fun bindView(view: View?, savedInstanceState: Bundle?) {
        super.bindView(view, savedInstanceState)
        // 绑定 EventBus
        EventBus.getDefault().register(this)
//         禁用刷新
//        swipeLayout.isEnabled = false
        // 设置分割线
        addItemDecoration()

        // 设置条目点击事件
        adapter.setOnItemClickListener { adapter, view, position ->
            //            L.d("当前位置s: $position")
//            Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show()
            // 获取会话
            val conversation = adapter.data[position] as Conversation
            // 获取用户信息
            val userInfo: UserInfo = conversation.targetInfo as UserInfo
            // 获取用户名
            val userName = userInfo.userName
            SingleActivity.newInstance(context!!, userName)
        }

        // 刷新数据
        swipeLayout.setOnRefreshListener {
            swipeLayout.isRefreshing = true
            updateData()
            // 设置刷新结束
            swipeLayout.isRefreshing = false
        }
    }

    /**
     * 添加列表条目分割线
     */
    private fun addItemDecoration() {
        // 默认分割线
        // recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        val divider = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
        context?.let { ContextCompat.getDrawable(it, R.drawable.item_divider)?.let { it1 -> divider.setDrawable(it1) } }
        recyclerView.addItemDecoration(divider)
    }

    override fun getContentLayout(): Int = R.layout.fragment_msg

    override fun inject(applicationComponent: IApplicationComponent?) {
        DaggerMsgComponent
            .builder()
            .applicationComponentImpl(applicationComponent as ApplicationComponentImpl)
            .build()
            .inject(this)
    }

    override fun setAdapter(): BaseQuickAdapter<*, *> = MsgAdapter()

    /**
     * 在线消息
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent) {
        L.d("有消息到来: ${event.message}")
//        val conversation = JMessageClient.getSingleConversation(event.message.fromUser.userName)
        updateData()
    }

    /**
     * 更新数据事件
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUpdateEvent(event: UpdateEvent) {
        updateData()
    }

    /**
     * 更新数据
     */
    private fun updateData() {
        // 获取数据
        val conversationList: List<Conversation> = JMessageClient.getConversationList()
        // 设置列表
        adapter.replaceData(conversationList)
    }

    override fun onDestroy() {
        // 解绑 EventBus
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }
}
